package edu.ccut.saturn.authority.core.dept;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import edu.ccut.saturn.component.DefaultComponent;
import edu.ccut.saturn.component.IParameterContext;

public class QueryDeptByName extends DefaultComponent {
	
	int flag = 0;

	public void execute(IParameterContext parameterContext) throws Exception {
		
		String deptName = (String)parameterContext.getParameterValue(0);
		List<Map<String, Object>> list = (ArrayList<Map<String, Object>>)parameterContext.getParameterValue(1);
		if(deptName != null){
			while(true){
				query(list, deptName);
				flag = 0;
				setLeaf(list);
				if(flag == 0){
					break;
				}
			}
		}
		
		parameterContext.setParameter(1, list);
	}
	
	
	private void query(List list, String deptName){
		
		if(list != null){
			for(int i = 0, n = list.size(); i < n; i++){
				Map<String, Object> map = (Map<String, Object>)list.get(i);
				if(Boolean.parseBoolean(map.get("leaf").toString())){
					//是叶子结点
					String text = map.get("text").toString();
					if(!text.contains(deptName)){
						list.remove(map);
						i--;
						n--;
					}
				} else {
					query((List)map.get("children"), deptName);
				}
			}	
		}
	}
	
	private void setLeaf(List list){
		if(list != null){
			for(int i = 0, n = list.size(); i < n; i++){
				Map<String, Object> map = (Map<String, Object>)list.get(i);
				List childrenList = (List)map.get("children");
				if(!Boolean.parseBoolean(map.get("leaf").toString())
						&& childrenList.size() == 0){
					map.put("leaf", true);
					flag++;
				} else {
					setLeaf((List)map.get("children"));
				}
			}
		}
	}
}
